<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>人口经济分析与空间分析管理后台</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body {
            background-color: #f8f9fa;
        }
        .header-bg {
            background-color: #0d6efd;
            color: white;
            padding: 20px 0;
            margin-bottom: 20px;
        }
        .content-card {
            margin-bottom: 20px;
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
        }
        .data-table-container {
            max-height: 400px;
            overflow-y: auto;
        }
        .btn-group-nav .btn {
            font-size: 1.1rem;
        }
        .nav-link.active {
            font-weight: bold;
            border-bottom: 3px solid #0d6efd;
        }
    </style>
</head>
<body>

    <header class="header-bg">
        <div class="container">
            <h1 class="text-center">人口经济分析与空间分析后端管理界面</h1>
            <p class="text-center lead">API服务状态: **http://localhost:5000**</p>
        </div>
    </header>

    <div class="container">

        <ul class="nav nav-tabs mb-4" id="mainTabs" role="tablist">
            <li class="nav-item" role="presentation">
                <button class="nav-link active" id="overview-tab" data-bs-toggle="tab" data-bs-target="#overview" type="button" role="tab">📊 概览 & 基础数据</button>
            </li>
            <li class="nav-item" role="presentation">
                <button class="nav-link" id="coupling-tab" data-bs-toggle="tab" data-bs-target="#coupling" type="button" role="tab">🔗 耦合协调度分析</button>
            </li>
            <li class="nav-item" role="presentation">
                <button class="nav-link" id="spatial-tab" data-bs-toggle="tab" data-bs-target="#spatial" type="button" role="tab">🗺️ GDP空间分析</button>
            </li>
        </ul>

        <div class="tab-content" id="mainTabsContent">

            <div class="tab-pane fade show active" id="overview" role="tabpanel" tabindex="0">
                <div class="card content-card">
                    <div class="card-header bg-primary text-white">
                        <h5>数据库表信息 (<span id="tableCount">0</span>个)</h5>
                    </div>
                    <div class="card-body">
                        <table class="table table-striped table-hover">
                            <thead>
                                <tr>
                                    <th>表名</th>
                                    <th>基础API路径</th>
                                    <th>单位</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody id="tableListBody">
                                <tr><td colspan="4" class="text-center">加载中...</td></tr>
                            </tbody>
                        </table>
                    </div>
                </div>

                <div class="modal fade" id="dataModal" tabindex="-1" aria-labelledby="dataModalLabel" aria-hidden="true">
                    <div class="modal-dialog modal-xl">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h5 class="modal-title" id="dataModalLabel"></h5>
                                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                            </div>
                            <div class="modal-body">
                                <p>单位: <strong id="dataModalUnit"></strong></p>
                                <p>总记录数: <strong id="dataModalTotal"></strong></p>
                                <div class="data-table-container">
                                    <table class="table table-bordered table-sm" id="dataDetailTable">
                                        </table>
                                </div>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="tab-pane fade" id="coupling" role="tabpanel" tabindex="0">
                <div class="card content-card">
                    <div class="card-header bg-success text-white">
                        <h5>耦合协调度分析结果查询</h5>
                    </div>
                    <div class="card-body">
                        <div class="row g-3 align-items-center mb-3">
                            <div class="col-auto">
                                <label for="couplingYearSelect" class="col-form-label">选择年份:</label>
                            </div>
                            <div class="col-auto">
                                <select class="form-select" id="couplingYearSelect">
                                    </select>
                            </div>
                            <div class="col-auto">
                                <button class="btn btn-success" id="loadCouplingDataBtn">加载分析数据</button>
                            </div>
                            <div class="col-auto">
                                <button class="btn btn-info" id="loadCouplingTrendBtn">加载全部年份趋势数据</button>
                            </div>
                        </div>

                        <div id="couplingResultArea">
                            <h6 class="mt-4">📊 统计信息 (<span id="couplingStatsYear"></span>年)</h6>
                            <pre id="couplingStats" class="bg-light p-3 rounded"></pre>

                            <h6 class="mt-4">📜 地区排名列表</h6>
                            <div class="data-table-container">
                                <table class="table table-bordered table-sm table-striped">
                                    <thead>
                                        <tr>
                                            <th>排名</th>
                                            <th>地区</th>
                                            <th>协调度 (D)</th>
                                            <th>协调等级</th>
                                            <th>发展类型</th>
                                            <th>耦合度 (C)</th>
                                            <th>综合指数 (T)</th>
                                            <th>人口指数 (U_p)</th>
                                            <th>GDP指数 (U_e)</th>
                                        </tr>
                                    </thead>
                                    <tbody id="couplingRegionsBody">
                                        <tr><td colspan="9" class="text-center">请选择年份并点击加载</td></tr>
                                    </tbody>
                                </table>
                            </div>

                            <h6 class="mt-4">📈 趋势数据</h6>
                            <div class="data-table-container" style="max-height: 200px;">
                                <pre id="couplingTrendData" class="bg-light p-3 rounded small"></pre>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="tab-pane fade" id="spatial" role="tabpanel" tabindex="0">
                <div class="card content-card">
                    <div class="card-header bg-danger text-white">
                        <h5>GDP空间分析 (Moran's I, LISA, Gi*)</h5>
                    </div>
                    <div class="card-body">
                        <p class="alert alert-warning">
                            **注意:** 空间分析数据需要手动触发生成。K=4近邻，排列检验次数 $\text{perm}=99$。
                        </p>

                        <div class="d-flex mb-3">
                            <button class="btn btn-danger me-3" id="refreshSpatialDataBtn">🚀 刷新/生成空间分析数据 (POST /api/spatial/refresh)</button>
                            <button class="btn btn-outline-danger" id="loadSpatialYearsBtn">🔄 加载可用年份</button>
                        </div>
                        
                        <div class="row g-3 align-items-center mb-3">
                            <div class="col-auto">
                                <label for="spatialYearSelect" class="col-form-label">选择已分析年份:</label>
                            </div>
                            <div class="col-auto">
                                <select class="form-select" id="spatialYearSelect">
                                    </select>
                            </div>
                            <div class="col-auto">
                                <button class="btn btn-primary" id="loadSpatialStatsBtn">加载统计信息</button>
                            </div>
                            <div class="col-auto">
                                <button class="btn btn-primary" id="loadSpatialGeoJsonBtn">查看 GeoJSON 数据</button>
                            </div>
                        </div>

                        <div id="spatialResultArea">
                            <h6 class="mt-4">📊 统计信息 (<span id="spatialStatsYear"></span>年)</h6>
                            <pre id="spatialStats" class="bg-light p-3 rounded"></pre>

                            <h6 class="mt-4">🗺️ GeoJSON 数据预览</h6>
                            <div class="data-table-container" style="max-height: 250px;">
                                <pre id="spatialGeoJson" class="bg-dark text-white p-3 rounded small"></pre>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

        </div>

    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        const API_BASE = '/api';

        // 辅助函数：显示通知
        function showNotification(message, type = 'primary') {
            alert(`[${type.toUpperCase()}] ${message}`);
        }

        // ===================================
        // 1. 概览 & 基础数据功能
        // ===================================

        async function fetchTables() {
            try {
                const response = await fetch(`${API_BASE}/tables`);
                const data = await response.json();

                if (data.code === 0 && data.data) {
                    const tableListBody = document.getElementById('tableListBody');
                    tableListBody.innerHTML = '';
                    document.getElementById('tableCount').textContent = data.data.length;

                    data.data.forEach(table => {
                        const row = tableListBody.insertRow();
                        row.insertCell().textContent = table.name;
                        row.insertCell().textContent = table.api_base_path;
                        row.insertCell().textContent = table.unit;
                        const actionCell = row.insertCell();
                        const btn = document.createElement('button');
                        btn.className = 'btn btn-sm btn-outline-primary';
                        btn.textContent = '查看数据';
                        btn.onclick = () => fetchTableData(table.name, table.unit);
                        actionCell.appendChild(btn);
                    });
                } else {
                    document.getElementById('tableListBody').innerHTML = '<tr><td colspan="4" class="text-center">加载表信息失败</td></tr>';
                }
            } catch (error) {
                console.error('Fetch tables error:', error);
                document.getElementById('tableListBody').innerHTML = `<tr><td colspan="4" class="text-center">网络错误: ${error.message}</td></tr>`;
            }
        }

        async function fetchTableData(tableName, unit) {
            try {
                const response = await fetch(`${API_BASE}/${tableName}?page=1&size=10`);
                const data = await response.json();

                const modalLabel = document.getElementById('dataModalLabel');
                const modalUnit = document.getElementById('dataModalUnit');
                const modalTotal = document.getElementById('dataModalTotal');
                const detailTable = document.getElementById('dataDetailTable');

                modalLabel.textContent = `${tableName} - 前10条记录`;
                modalUnit.textContent = unit || '无';
                modalTotal.textContent = data.total || 'N/A';
                detailTable.innerHTML = ''; // 清空表格

                if (data.code === 0 && data.data.length > 0) {
                    const columns = Object.keys(data.data[0]);
                    
                    // 填充表头
                    const thead = detailTable.createTHead();
                    const headerRow = thead.insertRow();
                    columns.forEach(col => {
                        const th = document.createElement('th');
                        th.textContent = col;
                        headerRow.appendChild(th);
                    });

                    // 填充表体
                    const tbody = detailTable.createTBody();
                    data.data.forEach(rowObj => {
                        const row = tbody.insertRow();
                        columns.forEach(col => {
                            row.insertCell().textContent = rowObj[col];
                        });
                    });
                } else {
                    detailTable.innerHTML = '<tr><td>无数据或加载失败</td></tr>';
                }

                new bootstrap.Modal(document.getElementById('dataModal')).show();

            } catch (error) {
                console.error(`Fetch ${tableName} data error:`, error);
                showNotification(`加载 ${tableName} 数据失败`, 'danger');
            }
        }


        // ===================================
        // 2. 耦合协调度分析功能
        // ===================================

        async function setupCouplingAnalysis() {
            try {
                // 1. 获取可用年份
                const yearsResponse = await fetch(`${API_BASE}/years`);
                const yearsData = await yearsResponse.json();
                const select = document.getElementById('couplingYearSelect');
                select.innerHTML = '';
                
                if (yearsData.success && yearsData.years) {
                    yearsData.years.forEach(year => {
                        const option = document.createElement('option');
                        option.value = year;
                        option.textContent = year;
                        select.appendChild(option);
                    });
                    // 默认选择最新的年份
                    if (yearsData.years.length > 0) {
                        select.value = yearsData.years[yearsData.years.length - 1];
                    }
                } else {
                    select.innerHTML = '<option value="">加载年份失败</option>';
                }
            } catch (error) {
                console.error('Setup coupling analysis error:', error);
            }

            document.getElementById('loadCouplingDataBtn').onclick = loadCouplingData;
            document.getElementById('loadCouplingTrendBtn').onclick = loadCouplingTrendData;
        }

        async function loadCouplingData() {
            const year = document.getElementById('couplingYearSelect').value;
            if (!year) return showNotification('请选择年份', 'warning');

            document.getElementById('couplingStatsYear').textContent = year;
            document.getElementById('couplingStats').textContent = '加载中...';
            document.getElementById('couplingRegionsBody').innerHTML = '<tr><td colspan="9" class="text-center">加载中...</td></tr>';
            
            try {
                // 加载统计信息和地区列表
                const regionsResponse = await fetch(`${API_BASE}/regions?year=${year}`);
                const regionsData = await regionsResponse.json();

                const dataResponse = await fetch(`${API_BASE}/data?year=${year}`);
                const dataData = await dataResponse.json();

                // 填充统计信息
                if (dataData.success) {
                    document.getElementById('couplingStats').textContent = JSON.stringify(dataData.statistics, null, 2);
                    showNotification(`${year}年耦合协调度统计信息加载成功`, 'success');
                } else {
                    document.getElementById('couplingStats').textContent = dataData.message || '加载失败';
                }

                // 填充地区排名
                const regionsBody = document.getElementById('couplingRegionsBody');
                regionsBody.innerHTML = '';
                if (regionsData.success && regionsData.regions) {
                    regionsData.regions.forEach((region, index) => {
                        const row = regionsBody.insertRow();
                        row.insertCell().textContent = index + 1;
                        row.insertCell().textContent = region.name;
                        row.insertCell().textContent = region.coordination_degree.toFixed(4);
                        row.insertCell().textContent = region.coordination_level;
                        row.insertCell().textContent = region.development_type;
                        row.insertCell().textContent = region.coupling_degree.toFixed(4);
                        row.insertCell().textContent = region.U_p.toFixed(4);
                        row.insertCell().textContent = region.U_e.toFixed(4);
                    });
                } else {
                    regionsBody.innerHTML = `<tr><td colspan="9" class="text-center">${regionsData.message || '地区列表加载失败'}</td></tr>`;
                }

            } catch (error) {
                console.error('Load coupling data error:', error);
                showNotification('加载耦合协调度数据时发生错误', 'danger');
            }
        }

        async function loadCouplingTrendData() {
            document.getElementById('couplingTrendData').textContent = '加载全部趋势数据中，请稍候...';
            try {
                const response = await fetch(`${API_BASE}/all_trend`);
                const data = await response.json();

                if (data.success) {
                    document.getElementById('couplingTrendData').textContent = JSON.stringify(data, (key, value) => {
                        // 截断长数组，防止页面卡顿
                        if (key === 'trend_data' && Array.isArray(value)) {
                            return `[Array: ${value.length} records. Displaying first 5 only] ${JSON.stringify(value.slice(0, 5))}`;
                        }
                        return value;
                    }, 2);
                    showNotification(`成功加载 ${data.total_records} 条趋势数据`, 'success');
                } else {
                    document.getElementById('couplingTrendData').textContent = data.message || '加载失败';
                }
            } catch (error) {
                console.error('Load trend data error:', error);
                showNotification('加载趋势数据时发生错误', 'danger');
                document.getElementById('couplingTrendData').textContent = `错误: ${error.message}`;
            }
        }


        // ===================================
        // 3. GDP空间分析功能
        // ===================================

        async function loadSpatialAvailableYears() {
            try {
                const response = await fetch(`${API_BASE}/spatial/available-years`);
                const data = await response.json();
                const select = document.getElementById('spatialYearSelect');
                select.innerHTML = '';

                if (data.status === 'success' && data.available_years.length > 0) {
                    data.available_years.forEach(year => {
                        const option = document.createElement('option');
                        option.value = year;
                        option.textContent = year;
                        select.appendChild(option);
                    });
                    select.value = data.available_years[data.available_years.length - 1];
                    showNotification(`成功加载 ${data.total_count} 个已分析年份`, 'success');
                } else {
                    select.innerHTML = '<option value="">暂无已分析年份 (请刷新数据)</option>';
                    showNotification(data.message || '加载可用年份失败', 'warning');
                }
            } catch (error) {
                console.error('Load spatial years error:', error);
                showNotification('加载空间分析可用年份时发生错误', 'danger');
            }
        }

        async function refreshSpatialData() {
            if (!confirm('确定要触发空间分析数据刷新吗？这可能需要几秒钟。')) return;
            
            showNotification('正在触发空间分析数据刷新...请等待。', 'info');
            try {
                const response = await fetch(`${API_BASE}/spatial/refresh`, { method: 'POST' });
                const data = await response.json();
                
                if (data.status === 'success') {
                    showNotification('空间分析数据刷新成功! 请点击 "加载可用年份" 查看结果。', 'success');
                    loadSpatialAvailableYears(); // 刷新年份列表
                } else {
                    showNotification(`数据刷新失败: ${data.message}`, 'danger');
                }
            } catch (error) {
                console.error('Refresh spatial data error:', error);
                showNotification('刷新空间分析数据时发生网络或服务器错误', 'danger');
            }
        }

        async function loadSpatialStats() {
            const year = document.getElementById('spatialYearSelect').value;
            if (!year) return showNotification('请选择已分析年份', 'warning');

            document.getElementById('spatialStatsYear').textContent = year;
            document.getElementById('spatialStats').textContent = '加载中...';

            try {
                const response = await fetch(`${API_BASE}/spatial/stats/${year}`);
                const data = await response.json();

                if (!data.error) {
                    document.getElementById('spatialStats').textContent = JSON.stringify(data, null, 2);
                    showNotification(`${year}年空间统计信息加载成功`, 'success');
                } else {
                    document.getElementById('spatialStats').textContent = data.error;
                    showNotification(`加载 ${year} 年统计信息失败`, 'warning');
                }
            } catch (error) {
                console.error('Load spatial stats error:', error);
                showNotification('加载空间统计信息时发生错误', 'danger');
            }
        }

        async function loadSpatialGeoJson() {
            const year = document.getElementById('spatialYearSelect').value;
            if (!year) return showNotification('请选择已分析年份', 'warning');

            document.getElementById('spatialGeoJson').textContent = '加载中...';

            try {
                const response = await fetch(`${API_BASE}/spatial/data/${year}`);
                const data = await response.json();

                // GeoJSON数据量可能很大，仅显示前几行
                if (data.type === 'FeatureCollection') {
                    const truncatedFeatures = data.features.slice(0, 2);
                    const previewData = {
                        type: data.type,
                        features_count: data.features.length,
                        preview_features: truncatedFeatures,
                        // 移除geometry属性，防止打印过长
                        message: `GeoJSON数据加载成功, 共 ${data.features.length} 个特征 (仅显示前2个的属性)`
                    };
                    document.getElementById('spatialGeoJson').textContent = JSON.stringify(previewData, (key, value) => {
                        // 在预览中移除geometry以保持简洁
                        return key === 'geometry' ? '[... Omitted Geometry Data ...]' : value;
                    }, 2);
                    showNotification(`${year}年 GeoJSON 数据预览成功`, 'success');
                } else {
                    document.getElementById('spatialGeoJson').textContent = JSON.stringify(data, null, 2);
                    showNotification(`加载 ${year} 年 GeoJSON 数据失败`, 'warning');
                }
            } catch (error) {
                console.error('Load spatial geojson error:', error);
                showNotification('加载空间 GeoJSON 数据时发生错误', 'danger');
            }
        }


        // ===================================
        // 4. 页面初始化
        // ===================================

        document.addEventListener('DOMContentLoaded', () => {
            // 1. 初始化基础数据
            fetchTables();

            // 2. 初始化耦合协调度分析
            setupCouplingAnalysis();

            // 3. 初始化空间分析
            loadSpatialAvailableYears();
            document.getElementById('refreshSpatialDataBtn').onclick = refreshSpatialData;
            document.getElementById('loadSpatialYearsBtn').onclick = loadSpatialAvailableYears;
            document.getElementById('loadSpatialStatsBtn').onclick = loadSpatialStats;
            document.getElementById('loadSpatialGeoJsonBtn').onclick = loadSpatialGeoJson;

            // 默认清空结果区域
            document.getElementById('couplingStats').textContent = '等待加载...';
            document.getElementById('couplingTrendData').textContent = '等待加载...';
            document.getElementById('spatialStats').textContent = '等待加载...';
            document.getElementById('spatialGeoJson').textContent = '等待加载...';
        });
    </script>
</body>
</html>